/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package dao;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import pojo.Loaitaikhoan;
import pojo.Taikhoan;
import util.HibernateUtil;
import util.MD5Encrypt;

/**
 *
 * @author WMThiet
 */
public class TaiKhoanDAO {

    public static boolean KiemTraTonTai(String username) {
        boolean bExist = true;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            String hql = "from Taikhoan tk where tk.tenTaiKhoan=:tenTK and tk.daXoa=:daXoa";
            Query query = session.createQuery(hql);
            query.setString("tenTK", username);
            query.setBoolean("daXoa", false);

            if (query.uniqueResult() == null) {
                bExist = false;
            }
        } finally {
            session.close();
        }
        return bExist;
    }

    public static boolean ThemTaiKhoanMoi(Taikhoan taiKhoan) {
        boolean bDone = false;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            taiKhoan.setMatKhau(MD5Encrypt.MD5(taiKhoan.getMatKhau()));
            session.beginTransaction();
            session.save(taiKhoan);
            session.getTransaction().commit();

            bDone = true;
        } catch (Exception ex) {
            session.getTransaction().rollback();
        } finally {
            session.close();
        }
        return bDone;
    }

    public static Taikhoan DangNhap(String tenTaiKhoan, String matKhau) {
        boolean bDone = false;
        Taikhoan tk = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            matKhau = MD5Encrypt.MD5(matKhau);
            String hql = "from Taikhoan tk where tk.tenTaiKhoan =:tenTK and tk.matKhau =:matKhau";
            Query query = session.createQuery(hql);
            query.setString("tenTK", tenTaiKhoan);
            query.setString("matKhau", matKhau);
            
            ArrayList<Taikhoan> ds = (ArrayList<Taikhoan>) query.list();
            tk = ds.get(0);
            tk.setDanhGia(TaiKhoanDAO.LayChiSoDanhGia(tk.getDiemTinCayBan() + tk.getDiemTinCayMua()));

        } catch (Exception ex) {
            tk = null;
        } finally {
            session.close();
        }
        return tk;
    }
    
    public static boolean ChangeAvatar(int matk, String avatar) {
        boolean kq = false;
        Session session = HibernateUtil.getSessionFactory().openSession();

        try {            
            session.beginTransaction();            
            Taikhoan tk = (Taikhoan)session.get(Taikhoan.class, matk);
            tk.setAvatar(avatar);
            session.update(tk);
            
            session.getTransaction().commit();
            kq = true;
            
        } catch (Exception ex) {
            session.getTransaction().rollback();
            kq = false;
        } finally {
            session.close();
        }
        return kq;
    }

    public static boolean ChangeMatKhau(Taikhoan tk, String oldPass, String newPass) {
        boolean kq = false;
        if (tk.getMatKhau().equals(MD5Encrypt.MD5(oldPass))) {
            Session session = HibernateUtil.getSessionFactory().openSession();
            Transaction transaction = null;
            try {
                transaction = session.beginTransaction();
                tk.setMatKhau(MD5Encrypt.MD5(newPass));
                session.update(tk);
                transaction.commit();
                kq = true;
            } catch (Exception ex) {
                transaction.rollback();
                System.err.println(ex);
            } finally {
                session.close();
            }
        }
        return kq;
    }

    public static String ResetMatKhau(String username) {

        String newPass = null;
        Session session = HibernateUtil.getSessionFactory().openSession();

        try {
            session.beginTransaction();
            String hql = "from Taikhoan tk where tk.tenTaiKhoan=:tenTK and tk.daXoa=:daxoa";
            Query query = session.createQuery(hql);
            query.setString("tenTK", username);
            query.setBoolean("daxoa", false);

            Taikhoan taiKhoan = (Taikhoan) query.uniqueResult();
            newPass = MD5Encrypt.MD5((new Date()).toString()).substring(0, 12);

            //Lưu lại password:
            taiKhoan.setMatKhau(MD5Encrypt.MD5(newPass));
            session.update(taiKhoan);
            session.getTransaction().commit();
        } catch (Exception e) {
            session.getTransaction().rollback();
        } finally {
            session.close();
        }

        return newPass;
    }

    public static String LayNoiDungMailResetMatKhau(String username) {
        StringBuilder bodyMail = new StringBuilder();

        bodyMail.append(String.format("Chào <strong>%s</strong>, <br />", username));
        bodyMail.append("Chúng tôi vừa nhận được yêu cầu trợ giúp đăng nhập từ bạn. Thông tin đăng nhập mới của bạn là: <br />");
        bodyMail.append(String.format(" => Tên đăng nhập : <strong>%s</strong> <br />", username));
        bodyMail.append(String.format(" => Mật khẩu mới : <strong>%s</strong> <br />", ResetMatKhau(username)));
        bodyMail.append("Bạn hãy sử dụng những thông tin đăng nhập và nên đổi lại mật khẩu của riêng bạn !");
        bodyMail.append("P2T Bid chúc bạn mua được những món hàng <b style='color:red;'>chất lượng - giá rẻ </b> ! <br />");
        bodyMail.append("--- Ban QT P2T Bid ---");

        return bodyMail.toString();
    }
    
    public static List<Taikhoan> LayNguoiChoiXuatSac(){
        Session session = HibernateUtil.getSessionFactory().openSession();
        List<Taikhoan> listTK = null;
        
        try {
            session.beginTransaction();
            String hql = "select dgtc.taikhoan from Daugiathanhcong dgtc group by dgtc.taikhoan.maTaiKhoan order by count(*) desc";
            Query query = session.createQuery(hql);
            query.setMaxResults(3);
            
            listTK = query.list();
            
            for (Taikhoan taikhoan : listTK) {
                taikhoan.setDanhGia(LayChiSoDanhGia(taikhoan.getDiemTinCayBan() + taikhoan.getDiemTinCayMua()));
            }
            
        } catch (Exception e) {
            listTK = null;
        } finally {
            session.close();
        }
        
        return listTK;
    }
    
    public static int LayChiSoDanhGia(float total){
        
        int level = 1;
        int listLevel[] = new int[5];
        listLevel[0] = 20;
        listLevel[1] = 50;
        listLevel[2] = 80;
        listLevel[3] = 150;
        listLevel[4] = 200;
        
        for(int i=0; i < listLevel.length; i ++){
            if(total >= listLevel[i])
            {
                level = i + 1;                
                break;
            }
        }
        
        return level;
    }
    
     public static Taikhoan LayTaiKhoan(String username) {
        Taikhoan tk = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            String hql = "from Taikhoan tk where tk.tenTaiKhoan=:tenTK and tk.daXoa=:daxoa";
            Query query = session.createQuery(hql);
            query.setString("tenTK", username);
            query.setBoolean("daxoa", false);

            tk = (Taikhoan) query.uniqueResult();

        } catch (Exception e) {
            session.getTransaction().rollback();
        } finally {
            session.close();
        }
        return tk;
    }
    
    public static long LaySoNguoiDangKyTheoThang(int month,int year){
        Session session = HibernateUtil.getSessionFactory().openSession();
        long num = 0;
        
        try {
            session.beginTransaction();
            String hql = "select count(*) from Taikhoan tk where month(tk.ngayDangKi) =:month and year(tk.ngayDangKi) =:year";
            Query query = session.createQuery(hql);
            query.setInteger("month", month);
            query.setInteger("year", year);
            
            num = (Long) query.uniqueResult();
            
        } catch (Exception e) {
            num = 0;
        } finally {
            session.close();
        }
        
        return num;
    }
    
    public static long[] LayThongKeThanhVienDangKyTrongNam(int nam){
        long[] listNum = new long[12];
        
        for(int i = 0; i < 12; i ++){
            listNum[i] = LaySoNguoiDangKyTheoThang(i + 1, nam);
        }
        
        return listNum;
    }
    
    public static List<Taikhoan> LayDSTaiKhoan(int soTKTrenTrang,int trangHienTai){
        Session session = HibernateUtil.getSessionFactory().openSession();
        List<Taikhoan> listTK = null;
        
        try {
            session.beginTransaction();
            String hql = "from Taikhoan tk where tk.daXoa = 0";
            Query query = session.createQuery(hql);
            
            if(soTKTrenTrang != -1){
                query.setFirstResult((trangHienTai -1)*soTKTrenTrang);
                query.setMaxResults(soTKTrenTrang);
            }
            listTK = query.list();
            
        } catch (Exception e) {
            listTK = null;
        } finally {
            session.close();
        }
        
        return listTK;
    }
    
    public static int DemSoTK(){
        List<Taikhoan> listTK = LayDSTaiKhoan(-1, 1);
        if(listTK == null)
            return 0;
        return listTK.size();
    }
    
    public static int tinhTrangTheoDSTK(int soTKTrenTrang) {
        int soTrang = 0;
        
        int soLuong = DemSoTK();
        
        if (soTKTrenTrang == -1) {
            soTrang = 1;
        } else {
            soTrang = soLuong / soTKTrenTrang;
            if (soLuong % soTKTrenTrang != 0) {
                soTrang++;
            }
        }
        return soTrang;
    }
    
    public static boolean  XoaTaiKhoan(int maTK) {
        boolean bDone = false;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            
            Taikhoan tk = (Taikhoan)session.get(Taikhoan.class, maTK);
            tk.setDaXoa(true);
            session.update(tk);
            
            session.getTransaction().commit();            
            bDone = true;

        } catch (Exception e) {
            session.getTransaction().rollback();
            bDone = false;
        } finally {
            session.close();
        }
        return bDone;
    }
    
    public static Taikhoan  LayTaiKhoan(int maTK) {
        Taikhoan tk = null;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            
            tk = (Taikhoan)session.get(Taikhoan.class, maTK);
            

        } catch (Exception e) {
            tk = null;
        } finally {
            session.close();
        }
        return tk;
    }

    public static boolean CapNhatTK(int maTK, int loaiTK, int daXoa) {
        boolean bDone = false;
        Session session = HibernateUtil.getSessionFactory().openSession();
        try {
            session.beginTransaction();
            
            Taikhoan tk = (Taikhoan)session.get(Taikhoan.class, maTK);
            Loaitaikhoan LoaiTK = (Loaitaikhoan)session.get(Loaitaikhoan.class, loaiTK);
            tk.setDaXoa(daXoa == 1);
            tk.setLoaitaikhoan(LoaiTK);
            
            session.update(tk);            
            session.getTransaction().commit();            
            bDone = true;

        } catch (Exception e) {
            session.getTransaction().rollback();
            bDone = false;
        } finally {
            session.close();
        }
        return bDone;
    }
}
